import Vue from 'vue'
import VueRouter from 'vue-router'

import axios from "../axios";
import store from "../store"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/common/Home.vue'),
    children: [
      {
        path: '/index',
        name: 'Index',
        meta:{
          title: '首页'
        },
        component: () => import('@/views/common/Index.vue')
      },
      {
        path: '/updatePass',
        name: 'UpdatePass',
        meta: {
          title: "修改密码"
        },
        component: () => import('@/views/common/UpdatePass.vue')
      },
      {
        path: '/sys/users',
        name: 'SysUser',
        component: () => import('@/views/sys/User.vue')
      },
      {
        path: '/sys/roles',
        name: 'SysRole',
        component: () => import('@/views/sys/Role.vue')
      },
      {
        path: '/sys/menus',
        name: 'SysMenu',
        component: () => import('@/views/sys/Menu.vue')
      },
      {
        path: '/pc/userinfo',
        name: 'PcUserinfo',
        component: () => import('@/views/pc/Userinfo.vue')
      },
      {
        path: '/pc/addressinfo',
        name: 'PcAddressinfo',
        component: () => import('@/views/pc/Addressinfo.vue')
      },
      {
        path: '/mew/order',
        name: 'MewOrder',
        component: () => import('@/views/mew/Order.vue')
      },
      {
        path: '/mew/orderdetail',
        name: 'MewOrderDetail',
        component: () => import('@/views/mew/OrderDetail.vue')
      },
      {
        path: '/mew/orderstatus',
        name: 'MewOrderStatus',
        component: () => import('@/views/mew/OrderStatus.vue')
      },
      {
        path: '/sc/stationinfo',
        name: 'ScStationinfo',
        component: () => import('@/views/sc/StationInfo.vue')
      },
      {
        path: '/sc/expresswrapping',
        name: 'ScExpressWrapping',
        component: () => import('@/views/sc/ExpressWrapping.vue')
      },
      {
        path: '/sc/order',
        name: 'ScStationOrder',
        component: () => import('@/views/sc/StationOrder.vue')
      },
      {
        path: '/dm/collect',
        name: 'DmCollect',
        component: () => import('@/views/dm/Collect.vue')
      },
      {
        path: '/dm/sending',
        name: 'DmSending',
        component: () => import('@/views/dm/Sending.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/common/Login.vue')
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
// router.beforeEach((to, from, next) =>{
//   //to：将要访问的路径；form：从哪个路径跳转而来；next：一个函数，放行 next() 强制跳转 next('/login')
//   if (to.path === '/login') return next();
//   // 先获取token
//   const tokenStr = window.sessionStorage.getItem('token')
//   if (!tokenStr) return next('/login')
//   next()
// })


//   动态绑定路由
router.beforeEach((to, from, next) => {

  let hasRoute = store.state.menus.hasRoutes
  let token = localStorage.getItem("token")

  if (to.path === '/login') {
    next()
  } else if (!token) {
    next({path: '/login'})
  } else if(token && !hasRoute) {
    axios.get("/sys/menu/nav", {
      headers: {
        Authorization: localStorage.getItem("token")
      }
    }).then(res => {
      console.log(res.data.data)
      // 拿到menuList
      store.commit("setMenuList", res.data.data.nav)
      // 拿到用户权限
      store.commit("setPermList", res.data.data.authoritys)
      console.log(store.state.menus.menuList)
      // 动态绑定路由
      let newRoutes = router.options.routes
      res.data.data.nav.forEach(menu => {
        if (menu.children) {
          menu.children.forEach(e => {
            // 转成路由
            let route = menuToRoute(e)
            // 把路由添加到路由管理中
            if (route) {
              newRoutes[0].children.push(route)
            }
          })
        }
      })
      router.addRoutes(newRoutes)
      hasRoute = true
      store.commit("changeRouteStatus", hasRoute)
    })
  }
  next()
})

// 导航转成路由
const menuToRoute = (menu) => {

  if (!menu.component) {
    return null
  }

  let route = {
    name: menu.name,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }
  route.component = () => import('@/views/' + menu.component + '.vue')

  return route
}

export default router
